/*
 * GameMap.cpp
 *
 *  Created on: Jun 20, 2012
 *      Author: The Almighty Eric
 */

#include "GameMap.h"

GameMap::GameMap()
{
	name = "";
	audio = "";
	w = h = 0;
	Chunks = std::list<MapChunk*>();
}

void GameMap::setbg(std::string bg)
{
	background = bg;
}

void GameMap::setname(std::string n)
{
	name = n;
}

void GameMap::setaudio(std::string a)
{
	audio = a;
}

void GameMap::setdimensions(int width, int height)
{
	w = width;
	h = height;
}

void GameMap::placeobject(int x, int y, int z, int w, int h, SDL_Surface *image, std::string s, bool fv, bool fh)
{
	Vect key = chunkhash(x,y,z);
	if(!ChunkExists(key))
	{
		Chunks.push_back(new MapChunk(key));
	}
	(*getChunk(key))->AddObject(new MapObject(x, y, z, w, h, image, s, fv, fh));
}

void GameMap::eraseobject(std::list<MapObject*>::iterator iter)
{
	if(*iter != NULL)
	{
		Vect key = chunkhash((*iter)->s.x,(*iter)->s.y,(*iter)->s.z);
		if(ChunkExists(key))
		{
			cit = getChunk(key);
			MapObject* target = *iter;
			(*cit)->RemoveObject(iter);
			delete target;
		}
	}
}

/*
 * This function is used to determine collisions for the purpose of removing
 * objects from their respective chunk lists
 */
std::list<MapObject*>::iterator GameMap::collisione(int mousex, int mousey, engine *e)
{
	SDL_Rect mouse = SDL_Rect();
	mouse.x = mousex;
	mouse.y = mousey;
	mouse.h = 1;
	mouse.w = 1;
	Vect key = chunkhash(mousex, mousey, e->elayer);
	if(ChunkExists(key))
	{
		for(it = (*getChunk(key))->getContents(); *it != NULL; it++)
		{
			if(e->CollisionCheck(mouse, (*it)->s.CollBox))
				return it;
		}
	}

	return it;
}

bool GameMap::collision(int objectx, int objecty, int w, int h, engine *e)
{
	SDL_Rect object = SDL_Rect();
	object.x = objectx;
	object.y = objecty;
	object.h = h;
	object.w = w;
	Vect key = chunkhash(objectx, objecty, e->elayer);
	if(ChunkExists(key))
	{
		for(it = (*getChunk(key))->getContents(); (*it) != NULL; it++)
		{
			if(e->CollisionCheck(object, (*it)->s.CollBox))
				return true;
		}
		return false;
	}
	else
		return false;
}

void GameMap::clearGameMap()
{
	//TODO: Get around to fixing this eventually
	// Clears GameMap and resets attributes to default
	/*for(cit = Chunks.begin(); cit != Chunks.end(); cit++)
	{
		for(it = ((*cit)->getContents())->begin(); it != ((*cit)->getContents())->end(); it++)
		{
			delete *it;
		}
		((*cit)->getContents())->clear();
	}
	Chunks.clear();*/
}

Vect GameMap::chunkhash(int x, int y, int z)
{
	Vect v;
	v.x = floor(x/400);
	v.y = floor(y/400);
	v.z = z;
	return v;
}

std::list<MapChunk*>::iterator GameMap::getChunk(Vect v)
{
	cit = Chunks.begin();
	while(cit != Chunks.end())
	{
		if((*cit)->isKey(v))
			return cit;
	}

	return Chunks.end();
}

bool GameMap::ChunkExists(Vect v)
{
	cit = Chunks.begin();
	while(cit != Chunks.end())
	{
		if((*cit)->isKey(v))
			return true;
	}
	return false;
}
